package com.shengqi.xinnongren.work.ui.home.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.adapter.BaseRecyclerAdapter;
import com.shengqi.xinnongren.common.adapter.SmartViewHolder;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.ArrayUtil;
import com.shengqi.xinnongren.common.utils.KeyBoardUtils;
import com.shengqi.xinnongren.common.utils.SPUtils;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.goods.activities.ShoppingCartActivity;
import com.shengqi.xinnongren.work.ui.home.adapter.CommonGoodsAdapter;
import com.shengqi.xinnongren.work.ui.home.model.GoodsBean;
import com.shengqi.xinnongren.work.ui.home.model.HotSearchBean;
import com.shengqi.xinnongren.work.ui.home.model.SearchBean;
import com.shengqi.xinnongren.work.ui.home.presenter.SearchPresenter;
import com.shengqi.xinnongren.work.ui.home.view.SearchView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 搜索
 */
public class SearchActivity extends BaseMvpActivity<SearchView, SearchPresenter> implements SearchView {

    private static final String EXTRA_CONTENT = "search_content";

    @BindView(R.id.edt_search)
    EditText edt_search;
    @BindView(R.id.rv_hot_search)
    RecyclerView mRvHotSearch;

    @BindView(R.id.fl_cart_container)
    FrameLayout mFlCartContainer;
    @BindView(R.id.tv_cart_num)
    TextView mTvCartNum;

    @BindView(R.id.rv_history_search)
    RecyclerView mRvHistorySearch;

    @BindView(R.id.rv_search_res)
    RecyclerView mRvSearchRes;

    @BindView(R.id.vg_empty)
    ViewGroup mVgEmpty;
    @BindView(R.id.rv_empty)
    RecyclerView mRvEmpty;
    @BindView(R.id.tv_no_history)
    TextView mTvNoHistory;

    private List<GoodsBean> mList;
    private CommonGoodsAdapter mAdapter;

    private String content; //搜索内容
    private BroadcastReceiver mReceiver;

    public static void start(Context context, String content) {
        Intent intent = new Intent(context, SearchActivity.class);
        intent.putExtra(EXTRA_CONTENT, content);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getCartNum();
            }
        };
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(mReceiver, new IntentFilter(MainActivity.ACTION_REFRESH_CART_NUM));
    }

    private void getCartNum() {
        if (UserManager.getInstance().isLogin())
            mPresenter.getShoppingCartNum();
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        content = intent.getStringExtra(EXTRA_CONTENT);
        if (content != null && !content.equals("")) {
            edt_search.setText(content);
            searchContent(content);
            saveHistory(content);
        }

        mList = new ArrayList<>();
        mAdapter = new CommonGoodsAdapter(this, mList);

        mRvSearchRes.setLayoutManager(new GridLayoutManager(this, 2));
        mRvSearchRes.setAdapter(mAdapter);

        mRvEmpty.setLayoutManager(new GridLayoutManager(this, 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvEmpty.setAdapter(mAdapter);
        showHistory();

        mRvSearchRes.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dy > 10) {
                    mFlCartContainer.animate().alpha(0f).translationY(mFlCartContainer.getHeight()).start();
                    mFlCartContainer.setEnabled(false);
                }
                if (dy < -10) {
                    mFlCartContainer.animate().alpha(1f).translationY(0).start();
                    mFlCartContainer.setEnabled(true);
                }
            }
        });
    }

    /**
     * 购物车
     */
    @OnClick(R.id.fl_cart_container)
    void fl_cart_container() {
        if (Global.checkLogin(this)) {
            startActivity(new Intent(this, ShoppingCartActivity.class));
        }
    }

    @Override
    protected void initData() {

        mPresenter.getHotSearch();
        getCartNum();

        edt_search.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == event.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                if (!edt_search.getText().toString().equals("")) {
                    searchContent(edt_search.getText().toString());
                }
            }
            return false;
        });

        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    mVgEmpty.setVisibility(View.GONE);
                    mRvSearchRes.setVisibility(View.GONE);
                    mFlCartContainer.setVisibility(View.GONE);
                    showHistory();
                }
            }
        });


    }

    private void searchContent(String content) {
        //保存至本地
        saveHistory(edt_search.getText().toString());
        KeyBoardUtils.closeKeybord(edt_search, this);
        mPresenter.getSearchList(content);
    }

    private void saveHistory(String content) {
        StringBuilder buffer = new StringBuilder();
        String history = (String) SPUtils.get(this, "search_history", "");
        if (history != null && !history.isEmpty()) {
            String[] keywords = history.split(",");
            HashSet<String> set = new HashSet<>();
            Collections.addAll(set, keywords);
            set.add(content);
            for (String s : set) {
                buffer.append(s);
                buffer.append(",");
            }
        } else {
            buffer.append(String.format("%s,", content));
        }
        String keyString = buffer.toString();
        SPUtils.put(this, "search_history", keyString.isEmpty() ? "" : keyString.substring(0, keyString.length()));
    }

    void showHistory() {
        String history = (String) SPUtils.get(this, "search_history", "");
        if (!TextUtils.isEmpty(history)) {

            mTvNoHistory.setVisibility(View.GONE);

            String[] split = history.split(",");
            List<String> historyList = new ArrayList<>();
            historyList.addAll(Arrays.asList(split));

            mRvHistorySearch.setAdapter(new BaseRecyclerAdapter<String>(historyList, R.layout.item_hot_search) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, String model, int position) {
                    holder.text(R.id.tv_title, model);
                    holder.itemView.setOnClickListener(v -> {
                        edt_search.setText(model);
                        searchContent(model);
//                        saveHistory(model);
                    });
                }
            });
            mRvHistorySearch.setLayoutManager(new GridLayoutManager(this, 3));
        } else
            mTvNoHistory.setVisibility(View.VISIBLE);
    }

    @Override
    protected SearchPresenter createPresenter() {
        return new SearchPresenter();
    }

    @Override
    public void showHotSearchList(List<HotSearchBean> list) {
        showHot(list);
    }

    private void showHot(List<HotSearchBean> hotSearch) {

        List<String> hotList = ArrayUtil.listConvertToStringList(hotSearch, HotSearchBean::getName);

        mRvHotSearch.setAdapter(new BaseRecyclerAdapter<String>(hotList, R.layout.item_hot_search) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, String model, int position) {
                holder.text(R.id.tv_title, model);
                holder.itemView.setOnClickListener(v -> {
                    edt_search.setText(model);
                    searchContent(model);
                });
            }
        });
        mRvHotSearch.setLayoutManager(new GridLayoutManager(this, 3));
    }

    @Override
    public void showSearchList(SearchBean bean) {
        List<GoodsBean> goodsList = bean.getComList();
        if (goodsList != null && goodsList.size() > 0 && bean.getIsSearch() == 1) {
            mVgEmpty.setVisibility(View.GONE);
            mRvSearchRes.setVisibility(View.VISIBLE);
            mFlCartContainer.setVisibility(View.VISIBLE);
            mList.clear();
            mList.addAll(goodsList);
            mAdapter.notifyDataSetChanged();

        } else {
            mVgEmpty.setVisibility(View.VISIBLE);
            mRvSearchRes.setVisibility(View.GONE);
            mFlCartContainer.setVisibility(View.GONE);
            mList.clear();
            mList.addAll(goodsList);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetShoppingCartNum(int num) {
        if (num > 0)
            mTvCartNum.setVisibility(View.VISIBLE);
        else
            mTvCartNum.setVisibility(View.INVISIBLE);
        mTvCartNum.setText(String.valueOf(num));
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }
}
